from flask import Flask, render_template,request,jsonify,redirect,send_from_directory
#from base.loggers import getLogHanderTime,getLogHandlerFile
import logging
import markdown,os,collections
import genai

app = Flask(__name__)
#app.logger.addHandler(getLogHanderTime())
#app.logger.addHandler(getLogHandlerFile())
#app.logger.setLevel(logging.CRITICAL)

app.logger.disabled = True
werkzeug_logger = logging.getLogger('werkzeug')
werkzeug_logger.disabled = True

token = genai.get_access_token()

cate_check = {"main_dishes": ("Main Dishes: The Heart of the Meal","Discover our exquisite collection of main dishes, designed to be the centerpiece of your dining experience.  Join us on a culinary adventure where every meal becomes a celebration of flavors and a gathering of loved ones."), "snacks": ("Snacks:  Life's Little Delights","Indulge in our selection of snacks that promise to brighten your day with bursts of flavor and joy, perfect for any time you need a little pick-me-up."), "salad": ("Salad: The Garden's Gift to Your Plate","A vibrant medley of fresh greens, crisp vegetables, and savory dressings, crafting a symphony of flavors that refreshes the palate and invigorates the spirit."), "soup":("Soup: The Warm Embrace of Comfort","A comforting hug in a bowl, simmered to perfection, blending rich flavors and wholesome ingredients that nourish the body and warm the soul."), "wheaten_food":("Wheaten Food: The Golden Harvest","A timeless tradition that brings families together, twisting and turning into endless possibilities, each noodle a canvas for the bold and comforting flavors of the world."), "breakfast":("Breakfast: The Sunrise Fuel for Your Day","The vibrant start to your day, where hearty classics meet innovative flavors to fuel your mornings with energy and delight."), "seafood":("Seafood: Treasures from the Ocean's Bounty","Savor the ocean's bounty with our freshest catches, crafting dishes that bring the coast to your kitchen and celebrate the sea's diverse flavors and textures."), "dessert":("Dessert: The Art of Crafting Sweet Moments","Where simple ingredients transform into sweet memories, one recipe at a time, capturing the warmth and joy of homemade treats that fill homes with love and delicious aromas."), "condiments":("Condiments: Color Palette for Taste","Each spoonful of sauce carefully blends the harmonious resonance between ingredients and seasonings."), "drinks":("Drinks: The Liquid Companion","Quench your thirst with our inspired mixology — from classic cocktails to refreshing mocktails and smoothies, our Drinks section is your go-to guide for beverages that perfectly complement your dining experience."), "appetizers":("The Prelude to Perfection","Tease your taste buds with our creative selection of starters – from crispy crostini to succulent shrimp cocktails, our appetizers set the perfect tone for an exquisite dining experience."), "side_dishes":("Side Dishes: The Supporting Cast of Sensations","Artfully blend flavors and textures to enhance the dining experience, making every meal a symphony of tastes.") }
index_topics = [
    ("Main Dishes","/recipes/main_dishes/1","/static/maincourse.jpg","The Heart of the Meal","Sirloin Steak, Rib-Eye Steak, Pork Chop, Salisbury Steak, Pork Roast..."),
    ("Snacks","/recipes/snacks/1","/static/snacks.jpg","Life's Little Delights"," Waffle, Grilled Cheese, Risotto, Quesadilla, Sushi..."),
    ("Salad","/recipes/salad/1","/static/salad.jpg","The Garden's Gift to Your Plate","Ham Salad, Egg Salad, Red Potato Salad, Turkey Salad, Shrimp Salad..."),
    ("Soup","/recipes/soup/1","/static/soup.jpg","The Warm Embrace of Comfort","Clam Chowder, Cabbage Soup, Bean Soup, Fish Chowder , Potato Soup..."),
    ("Wheaten Food","/recipes/wheaten_food/1","/static/pasta.jpg","The Golden Harvest","Nachos, Omelet, Pizza, Hot Dogs, Pesto Pasta..."),
    ("Breakfast","/recipes/breakfast/1","/static/breakfast.jpg","The Sunrise Fuel for Your Day","Alfredo, Sandwiches, Meatball, Green Peas, Grain..."),
    ("Seafood","/recipes/seafood/1","/static/seafood.jpg","Treasures from the Ocean's Bounty","Tuna, Lobster, Crab, Tilapia, Swordfish..."),
    ("Dessert","/recipes/dessert/1","/static/baking.jpg","The Art of Crafting Sweet Moments","Muffin, Bread, Pie, Cookie, Mousse..."),
    ("Condiments","/recipes/condiments/1","/static/sauce.jpg","Color Palette for Taste","Sauces, Dips, Dressings, Paste, Salas..."),
    ("Drinks","/recipes/drinks/1","/static/drinks.jpg","The Liquid Companion","Beer, Vodka, Shot, Lemonade, Gin..."),
    ("Appetizers","/recipes/appetizers/1","/static/appetizers.jpg","The Prelude to Perfection","Ceviche, Bruschetta, Tapas, Caprese Skewers, Oysters..."),
    ("Side Dishes","/recipes/side_dishes/1","/static/sidedishes.jpg","The Supporting Cast of Sensations","Salami, Baked Mushroom, Potato Fries, Garlic Bread, Grilled Asparagus...")
]
# 去掉无图片内容
nopic = set([])
for line in os.popen("ls recipes/*.md").read().split("\n"):
    if "/" not in line: continue
    name = line.split("/")[1].split(".")[0]
    nopic.add(name.strip())
for line in os.popen("ls static/.").read().split("\n"):
    if "." in line or line.isdigit() == False: continue
    if line in nopic: nopic.remove(line.strip())

# 加载分类列表
id_dict = {}
for filename in list(os.walk("./listpack"))[0][2]:
    for line in open("./listpack/%s"%filename,"r"):
        items = line.strip().split("\t")
        if items[0] in nopic: continue
        name = items[1].lower().replace(" ","_").replace("'","")
        id_dict[name] = items[0]

@app.route('/recipe/<string:rid>')
def recipe(rid):
    pics = []
    num = id_dict[str(rid)] if str(rid) in id_dict else ""
    with open('recipes/%s.md'%(num), 'r') as file:
        recipe_content = file.read().replace("®","")
    tmp = recipe_content.split("\n")
    title = tmp[0].replace("**","")
    recipe_content = "\n".join(tmp[1:])
    if os.path.exists("./static/%s"%(num)):
        pics = sorted([ "/static/%s/%s"%(num,fname) for fname in list(os.walk("./static/%s"%(num)))[0][2] ])
    return render_template('recipes.html', recipe_title=title, content=markdown.markdown(recipe_content), pics_head=pics[0] if len(pics) > 0 else "",pics=pics[1:] if len(pics) > 0 else [])

@app.route('/')
def index():
    return render_template('index.html',topics=index_topics)

@app.route('/book')
def book():
    popular = []
    for num in [1513,2701,145]:
        cont = open("./static/pdf/output_%d.txt"%(num),"r").read().split("\n")
        popular.append([cont[1],cont[0],cont[2],'/pdf/output_%d.pdf'%(num)])
    latest = []
    for num in [74243,74239,74235]:
        cont = open("./static/pdf/output_%d.txt"%(num),"r").read().split("\n")
        latest.append([cont[1],cont[0],cont[2],'/pdf/output_%d.pdf'%(num)])
    a_list = []
    for num in [24117,68105,66937]:
        cont = open("./static/pdf/output_%d.txt"%(num),"r").read().split("\n")
        a_list.append([cont[1],cont[0],cont[2],'/pdf/output_%d.pdf'%(num)])
    f_list = []
    for num in [27916,36536,56661]:
        cont = open("./static/pdf/output_%d.txt"%(num),"r").read().split("\n")
        f_list.append([cont[1],cont[0],cont[2],'/pdf/output_%d.pdf'%(num)])
    k_list = []
    for num in [62286,1795,4215]:
        cont = open("./static/pdf/output_%d.txt"%(num),"r").read().split("\n")
        k_list.append([cont[1],cont[0],cont[2],'/pdf/output_%d.pdf'%(num)])
    p_list = []
    for num in [42011,60513,2995]:
        cont = open("./static/pdf/output_%d.txt"%(num),"r").read().split("\n")
        p_list.append([cont[1],cont[0],cont[2],'/pdf/output_%d.pdf'%(num)])
    u_list = []
    for num in [50620,25351,2664]:
        cont = open("./static/pdf/output_%d.txt"%(num),"r").read().split("\n")
        u_list.append([cont[1],cont[0],cont[2],'/pdf/output_%d.pdf'%(num)])
    return render_template('book.html',hot=popular,latest=latest,a_list=a_list,f_list=f_list,k_list=k_list,p_list=p_list,u_list=u_list)

@app.route('/robot_home')
def robot_home():
    info = {'中国粤菜':'以选材广泛、制作精细和追求食材原味而著称。粤菜擅长炖、蒸、炒、烤等烹饪方法。','中国鲁菜':'以其烹饪技法的丰富性和对原料质量的严格要求而闻名。鲁菜注重调味品的运用，尤其是酱油、醋、葱的调味作用。','中国川菜':'以其鲜明的口味、多变的烹饪技巧和大胆的香料使用而著名，尤其是花椒和辣椒的使用，有“麻、辣、烫”的特点。','淮扬菜':'以其精细的刀工、考究的摆盘和追求食物本身的鲜美而闻名。淮扬菜讲究食材的新鲜和季节性。','法国菜':'以其精致的烹饪技巧和丰富多样的美食闻名，被认为是世界高级料理的典范。','意大利菜':'以面食、比萨、意面和地中海风味著称，如那不勒斯比萨和托斯卡纳炖肉。','西班牙菜':'包括著名的海鲜饭、塔帕斯和加泰罗尼亚地区的卡斯提亚风味。','希腊菜':'以橄榄油、新鲜蔬菜和海鲜为主，代表菜有希腊沙拉和穆萨卡。','土耳其菜':'拥有丰富的烤肉、肉丸、甜点如果仁蜜饼和土耳其肉包。','印度菜':'以其香料闻名，如咖喱、烤肉和各种素食佳肴。','日本菜':'包括寿司、刺身、天妇罗和拉面，强调食材的新鲜度和季节性。','韩国菜':'以泡菜、烧烤和石锅拌饭为代表，注重发酵食品和辣味。','泰国菜':'结合了酸、甜、咸和辣的味道，如绿咖喱、冬阴功汤和芒果糯米饭。','越南菜':'包括河粉、越南春卷和牛肉粉，注重清淡和草本香料。','墨西哥菜':'以其玉米饼、塔科斯、辣椒炖肉和鳄梨酱著称。','巴西菜':'以巴西烤肉、黑豆炖肉和木薯粉为特色。','阿根廷菜':'以烤肉、乳酪馅饼和马黛茶闻名。','秘鲁菜':'包括烤豚鼠、酸橘汁腌鱼和藜麦。','埃及菜':'以福尔、库萨和鸽子饭为特色。','摩洛哥菜':'以塔吉锅菜、库斯库斯和薄荷茶著称。','伊朗菜':'强调香料、坚果和果干，如波斯炖肉和烤肉串。','俄罗斯菜':'包括罗宋汤、俄式肉冻和黑鱼子酱。','德国菜':'以其香肠、猪肘和黑啤酒著称。','波兰菜':'包括饺子、烤猪蹄和酸菜。','捷克菜':'以炖肉、土豆和啤酒为主。','匈牙利菜':'强调辣椒粉、炖肉和鹅肝。','瑞典菜':'包括肉丸、鲱鱼和圣诞大餐。','挪威菜':'以鲑鱼、熏肉和鱼子酱为特色。','丹麦菜':'包括开放式三明治、烟熏鲑鱼和丹麦酥。','英国菜':'以其炸鱼薯条、肉派和英式早餐著称。','爱尔兰菜':'以炖肉、土豆泥和黑啤酒闻名。','澳洲菜':'包括袋鼠肉、澳洲坚果和肉派。','新西兰菜':'强调海鲜、鹿肉和奇异果。','南非菜':'包括烤肉、玉米粥和鳄梨。','肯尼亚菜':'以乌加里、炖肉和茶为特色。','阿拉伯菜':'强调米饭、烤肉和椰枣。','马来菜':'结合了马来、中国和印度的影响，如椰浆饭和叻沙。','新加坡菜':'包括辣椒蟹、海南鸡饭和炒粿条。','菲律宾菜':'以烤肉、酸辣汤和芒果为特色。','印尼菜':'强调咖喱、烤肉和印尼炒饭。','美式菜':'龙虾、蛤蜊浓汤、烤火鸡、苹果派和波士顿奶油派。'}
    return render_template('robot_home.html',ingredients=['西红柿','黄瓜','胡萝卜','白菜','菠菜','生菜','芹菜','青椒','红椒','西兰花','茄子','豆角','芦笋','春笋','土豆','南瓜','冬瓜','苦瓜','丝瓜','上海青','藕','山药','荷兰豆','豌豆','菜心','韭菜','香菜','空心菜','甜菜根','菜花','猪肉','牛肉','羊肉','鸡肉','鸭肉','猪里脊','猪五花肉','猪排骨','牛排','牛腩','羊排','鸡胸肉','鸡腿肉','鸭胸肉','鸭腿肉','鲜虾','对虾','鳕鱼','三文鱼','鲈鱼','带鱼','鲫鱼','鳝鱼','螃蟹','贻贝','扇贝','蛤蜊','海参','海蜇','章鱼','豆腐','豆腐干','豆腐皮','百叶','豆腐脑','豆浆','素鸡','素鹅','豆腐乳','扁豆酱','牛奶','酸奶','奶油','奶酪','酸乳酪','炼乳','马苏里拉奶酪','切达奶酪','希腊酸奶','芝士片','火腿','培根','热狗','熏肉','肉丸','香肠','腌制黄瓜','午餐肉','罐装金枪鱼','罐装沙丁鱼','方便面','速冻饺子','速冻汤圆','速冻馒头','速冻包子','速冻春卷','速冻水饺','冷冻水果','冷冻蔬菜','冷冻薯条'],cuisines=info.items())

@app.route('/getai',methods=['POST'])
def get_ai():
    if request.is_json:
        data = request.get_json()
        if 'ingredients' in data and 'cuisine' in data:
            ingredients = data['ingredients']
            theme = data['cuisine']
            content = genai.genai(token,ingredients,theme)
            return jsonify(content), 200
        else:
            return jsonify({'error': 'Missing ingredients or cuisine in the request'}), 400
    else:
        return jsonify({'error': 'Request does not contain JSON data'}), 400

@app.route('/recipes/<string:cate>/<int:pagenum>')
def category(cate,pagenum):
    cate_name = cate if cate in cate_check.keys() else "main_dishes"
    detail = {}
    num = 0
    for i,item in enumerate(catelist[cate_name].items()):
        num += 1
        if i < (pagenum - 1) * 60 or i >= pagenum * 60: continue
        detail[item[1]] = [ item[1].lower().replace(" ","_").replace("'",""), item[0], short_desc[item[0]] ]
    totalnum = int((num - 1) / 60) + 1
    return render_template('list.html', title=cate_check[cate_name][0].split(":")[0],cate_title=cate_check[cate_name][0], desc=cate_check[cate_name][1], detail=detail.items(),pagenum=pagenum,cate=cate,totalnum=totalnum)

@app.route('/favorites.icon')
def favorites_icon():
    return send_from_directory('./static/','favorites.icon')

@app.route('/robots.txt')
def robots_txt():
    return send_from_directory('./','robots.txt')

@app.route('/pdf/<string:pdf>')
def download_pdf(pdf):
    return send_from_directory('./static/pdf',pdf)

from whoosh.index import create_in
from whoosh.fields import Schema, TEXT, ID
from whoosh.index import open_dir
from whoosh.qparser import QueryParser
@app.route('/search',methods=['GET','POST'])
def search():
    retvals = []
    words = "_blank_"
    if request.method == 'POST':
        result = request.form
        words = result.get('word', '_blank_')
    elif request.method == 'GET':
        result = request.args
        words = result.get('word', '_blank_')
    with ix.searcher() as searcher:
        query = QueryParser("content", ix.schema).parse(words)
        results = searcher.search(query, limit=100)
        retvals = { result['title']: [result['title'].lower().replace(" ","_").replace("'",""),int(result['path']),short_desc[result['path']]] for result in results }
    if len(retvals) > 0: return render_template('search_results.html', cate_title="Search For: %s"%words, detail=retvals.items())
    return render_template('search_results.html',cate_title="%s Not Found."%words, detail=[])

def create_search_index():
    schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
    if not os.path.exists("indexdir"):
        os.mkdir("indexdir")
    ix = create_in("indexdir", schema)
    return ix

#读取列表
catefile = ['appetizers.txt', 'breakfast.txt', 'condiments.txt',  'dessert.txt',  'drinks.txt',  'main_dishes.txt',  'salad.txt',  'seafood.txt',  'side_dishes.txt',  'snacks.txt',  'soup.txt',  'wheaten_food.txt']
catelist = collections.defaultdict(lambda: {})
short_desc = {}
totallist = {}
for cname in catefile:
    for line in open("./listpack/"+cname,"r"):
        item = line.strip().split("\t")
        catelist[cname.split(".")[0]][item[0]] = item[1]
        short_desc[item[0]] = item[2]
        totallist[item[0]] = item[1]

#索引文档
ix = create_search_index()
writer = ix.writer()
for line in os.popen("ls recipes/*.md").read().split("\n"):
    if "/" not in line: continue
    num = line.split("/")[1].split(".")[0]
    if num.isdigit() == False: continue
    if num in nopic: continue
    if num not in totallist: continue
    content = open(line.strip(),'r').read()
    title = totallist[num]
    content = "\n".join(content.split("\n")[1:]).replace("*","")
    writer.add_document(title=title, path=num, content=content)
writer.commit()

if __name__ == '__main__':
    #serve(app, host='0.0.0.0', port=80)    
    app.run(host='127.0.0.1',port=5000,debug=False, use_reloader=False)

